package org.zxp.onedoteight.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @program: effectiveJava
 * @description:
 * @author: X-Pacific zhang
 * @create: 2019-10-08 17:37
 **/
public class StreamSplit {
    //按每3个一组分割
    private static final Integer MAX_NUMBER = 5000;

    /**
     * 计算切分次数
     */
    private static Integer countStep(Integer size) {
        return (size + MAX_NUMBER - 1) / MAX_NUMBER;
    }

    static List<Integer> getData(){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            list.add(new Random().nextInt());
        }
        return list;
    }


    public static void main(String[] args) {
        List<Integer> list = getData();
        int limit = countStep(list.size());
        //方法一：使用流遍历操作
        long l1 = System.currentTimeMillis();
        List<List<Integer>> mglist = new ArrayList<>();
        Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
            mglist.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList()));
        });
        long l2 = System.currentTimeMillis();

//        System.out.println(mglist);

        //方法二：获取分割后的集合
        List<List<Integer>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());

//        System.out.println(splitList);
        long l3 = System.currentTimeMillis();

        splitList.forEach(lst -> {
            if(lst.size() != MAX_NUMBER){
                System.err.println("error"+lst.size());
            }
        });

//        splitList.forEach(lst -> {
//                System.err.println(lst.size());
//        });

        System.out.println("No2:"+(l3-l2));
        System.out.println("No1:"+(l2-l1));
    }
}
